﻿using System;
using System.Collections;
using System.Net;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.ServiceProcess;
using System.Threading;
using Sendmail.Server;
using log4net;
using log4net.Config;

namespace Service
{
    public partial class Service1 : ServiceBase
    {

        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Thread thread1  ;
        private TcpChannel channel;
        public SmtpServer SmtpServer1 { get; private set; }
        public Service1()
        {
            InitializeComponent();
            XmlConfigurator.Configure();
            this.ServiceName = "SendMailSvc";
        }

        protected override void OnStart(string[] args)
        {
            thread1 = new Thread(this.Run);
            thread1.Start();

            Log.Debug("Application loaded successfully.");

//            HttpServerChannel serverChannel = new HttpServerChannel(8234);
//            ChannelServices.RegisterChannel(serverChannel, false);
//
//
//            RemotingServices.Marshal(SmtpServer1, "CountingService.rem");

            BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
            provider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary props = new Hashtable();
            props["port"] = 9934;
            channel = new TcpChannel(props, null, provider);
            ChannelServices.RegisterChannel(channel);
           // RemotingConfiguration.RegisterWellKnownServiceType(typeof(CustomType), "CustomType", WellKnownObjectMode.Singleton);
            RemotingServices.Marshal(SmtpServer1, "SendMailSvc");

            



        }
        public void Run()
        {
            SmtpServer1 = new SmtpServer(IPAddress.Any, 25);
        }
        protected override void OnStop()
        {
            //thread1.Abort();
            SmtpServer1.ServerIsWorking = false;
            SmtpServer1.ServerListenerIsWorking = false;
            thread1.Abort();
            
            //ChannelServices.UnregisterChannel(channel);
        }
    }
}
